package com.automannn.cas.practice.casServerWebflow;

import com.google.common.collect.Sets;
import nz.net.ultraq.thymeleaf.layoutdialect.LayoutDialect;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.ServletContextAware;
import org.thymeleaf.dialect.IDialect;
import org.thymeleaf.spring4.ISpringTemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;

import javax.servlet.ServletContext;
import java.nio.charset.StandardCharsets;

/**
 * @author chenkh
 * @time 2022/1/1
 */

@Configuration
@Order(-3001)
public class ThymeleafAdapterConfiguration implements ApplicationContextAware {
    public ThymeleafAdapterConfiguration() {
    }

    private ApplicationContext applicationContext;


    @Bean
    public ITemplateResolver automannnTemplateResolver(){
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("classpath:templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        templateResolver.setCacheable(false);
        templateResolver.setApplicationContext(this.applicationContext);
        templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        return templateResolver;
    }

    @Bean
    public IDialect automannnDialect(){
        LayoutDialect layout = new LayoutDialect();
        return layout;
    }

    @Bean
    public SpringTemplateEngine automannnTemplateEngine(ITemplateResolver automannnTemplateResolver){
        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
        springTemplateEngine.setTemplateResolver(automannnTemplateResolver);

        springTemplateEngine.setAdditionalDialects(Sets.newHashSet(automannnDialect()));
        return springTemplateEngine;
    }


    @Bean
    public ThymeleafViewResolver automannnViewResolver(ISpringTemplateEngine templateEngine){
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine);
        viewResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        return viewResolver;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext= applicationContext;
    }
}
